<template>
  <div>
    <editor
    :id="tinymceId"
      api-key="1zk4fbpkjdy13in9od3r4ilumg6ipfsg9n7u8c4y8skkrgv9"
      :init="options"
    />
  </div>
</template>

<script>
import Editor from "@tinymce/tinymce-vue";
import request from "@/utils/request";

export default {
  components: {
    editor: Editor,
  },
  props: {
    id: {
      type: String,
      default: function () {
        return (
          "vue-tinymce-" +
          +new Date() +
          ((Math.random() * 1000).toFixed(0) + "")
        );
      },
    },
    value: {
      type: String,
      default: "",
    },
  },

  watch: {
    value(val) {
      if (this.hasInit) {
        this.$nextTick(() =>
          window.tinymce.get(this.tinymceId).setContent(val || "")
        );
      }
    },
  },
  data() {
    return {
      tinymceId: this.id,
      hasInit: false,
      hasChange: false,
      options: {
        height: 500,
        menubar: false,
        language: "zh_CN",
        plugins: [
          "advlist autolink lists link image charmap print preview anchor imagetools",
          "searchreplace visualblocks fullscreen",
          "insertdatetime media table help wordcount",
        ],
        toolbar:
          "undo redo | formatselect | bold italic forecolor backcolor | \
           alignleft aligncenter alignright alignjustify | \
           bullist numlist outdent indent | image media| removeformat",
        powerpaste_word_import: "propmt",
        powerpaste_html_import: "propmt",
        powerpaste_allow_local_images: true,
        powerpaste_keep_unsupported_src: true,
        paste_data_images: true,
        images_upload_handler: (blobInfo, success, failure) => {
          this.upload(blobInfo.blob(), (e) => {
            success(e);
          });
        },
        init_instance_callback: (editor) => {
          if (this.value) {
            editor.setContent(this.value);
          }
          this.hasInit = true;
          // 监听富文本内容的改变 将变化传回richtext的v-model
          editor.on("NodeChange Change KeyUp SetContent", () => {
            this.hasChange = true;
            this.$emit("input", editor.getContent());
          });
        },
      },
    };
  },

  methods: {
    upload(img, fn) {
      let data = new FormData();
      data.append("f1", img);

      let config = {
        method: "post",
        url: "/upPic",
        data: data,
      };

      request(config).then((res) => {
        if (res.message == "OK") {
          fn && fn(process.env.VUE_APP_BASE_API + "/" + res.raw);
        } else {
          console.log("图片上传失败");
          fn && fn("");
        }
      });
    },

    set_content(val) {
      window.tinymce.get(this.tinymceId).setContent(val || "")
    }
  },
};
</script>